
#include "Texture2D.h"

Texture2D::Texture2D()
{
	mFilename = NULL;	
	mData = NULL;
}

Texture2D::~Texture2D()
{
	if(mFilename != NULL)
	{
		// why there is an error here.
		//delete mFilename;
		//mFilename = NULL;
	}

	if(mData != NULL)
	{
		delete mData;
		mData = NULL;
	}

}

void Texture2D::ConvertBGRtoRGB()
{
	const DWORD BitmapLength = mSizeX * mSizeY * 3;
	byte temp;

	for(DWORD i=0; i < BitmapLength; i+=3)
	{
		temp = mData[i];
		mData[i] = mData[i+2];
		mData[i+2] = temp;
	}

}

bool Texture2D::LoadFile(const char* inFilename)
{

	//checking for a existing file can go into utilities.
	if(!inFilename)		return false;

	mFilename = new char[strlen(inFilename)];
	strcpy(mFilename,inFilename);

	FILE *File = NULL;
	fopen_s(&File,mFilename,"r");
	if(File == NULL)
		return false;
	else
		fclose(File);

	BITMAPINFO BMInfo;
	const HDC hdc = wglGetCurrentDC();

	if(mData != NULL) delete[] mData;

	BMInfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
	BMInfo.bmiHeader.biBitCount = 0;

	HANDLE DIBHandle = LoadImage(0,mFilename,IMAGE_BITMAP,0,0,LR_DEFAULTCOLOR | LR_CREATEDIBSECTION | LR_LOADFROMFILE);

	if(DIBHandle == NULL)
		return false;

	GetDIBits(hdc,(HBITMAP)DIBHandle,0,0,NULL,&BMInfo,DIB_RGB_COLORS);
	mSizeX = BMInfo.bmiHeader.biWidth;
	mSizeY = BMInfo.bmiHeader.biHeight;
	BMInfo.bmiHeader.biBitCount = 24;
	BMInfo.bmiHeader.biCompression = BI_RGB;
	const DWORD BitmapLength = mSizeX * mSizeY  * 3;
	mData = new byte[BitmapLength];

	if(GetDIBits(hdc,(HBITMAP)DIBHandle,0,mSizeY, mData, & BMInfo, DIB_RGB_COLORS))
	{
		mIsReady = true;
		ConvertBGRtoRGB();
	}

	DeleteObject(DIBHandle);

	return mIsReady;
}